package com.chenjinyan.back.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author chenjinyan
 * @version 1.0
 */
public class ImageUtil {


    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);


    public static String saveImg(MultipartFile multipartFile, String path, String username, String reqPath) throws IOException {
        String reqPaths = reqPath;
        //处理图片
        String fileName;
        if (multipartFile.isEmpty() || StringUtils.isEmpty(multipartFile.getOriginalFilename())) {
            throw new DescribeException(ExceptionEnum.IMG_NAME_IS_NULL);
        }
        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            throw new DescribeException(ExceptionEnum.CONTENT_TYPE_IS_NULL);
        }
        String rootFileName = multipartFile.getOriginalFilename();
        logger.info("上传图片:name={},type={}", rootFileName, contentType);

        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
        fileName = username + "_" + getRandomFileName() + ".png";
        reqPath = reqPaths + fileName;
        logger.info("图片访问路径:realPath={}", reqPath);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();

        return reqPath;
    }


    private static String getRandomFileName() {

        SimpleDateFormat simpleDateFormat;

        simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

        Date date = new Date();

        String str = simpleDateFormat.format(date);

        Random random = new Random();
        // 获取5位随机数
        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;

        return rannum + str;
    }

}
